// 获取当前地址栏id
const id = GetQueryString('id') || -1;
let getStorageList = localStorage.getItem('list') || '[]';
let list = JSON.parse(getStorageList);
const item = list[id] || undefined;
if(item) {

  function getValue(nameVal, value, n) {
    let ipt = null;
    // n=0,获取select;	n=1,获取textarea
    if (n === 0) {
      ipt = document.querySelector(`select[name = ${nameVal}]`)
    } else if (n === 1) {
      ipt = document.querySelector(`textarea[name = ${nameVal}]`);
    }else {
      ipt = document.querySelector(`input[name = ${nameVal}]`);
    }
    ipt.value = value;
  }
  function setRadio(RadioName) {
    var selects = document.querySelectorAll(`input[name='${RadioName}']`);
    for (var i = 0; i < selects.length; i++) {
      if (selects[i].value === item[RadioName]) {
        selects[i].checked = true;
        break;
      }
    }
  }

// 回显
  for (let key in item) {
    if (key === 'major') {
      getValue(key, item[key], 0);
    } else if (key === 'intro') {
      getValue(key, item[key], 1);
    } else if (key === 'state' || key === 'way') {
      setRadio(key);
    } else {
      getValue(key, item[key]);
    }
  }

  !function (t, e) {
    let list = localStorage.getItem('list') || [];
    if (list.length !== 0) {
      list = JSON.parse(list);
    }

    function handleClickSubmit(event) {
      const params = serializeForm('form');
      console.log(params)
      itemOfList(params);
      event.preventDefault();
    }

    function itemOfList(item) {
      // list.push(item);
      list.splice(Number(id), 1, item);
      let listChangeString = JSON.stringify(list);
      localStorage.setItem('list', listChangeString);
      t.location.href = 'courselist.html'
    }

    const form = e.getElementById('form');
    form.addEventListener('submit', handleClickSubmit);
  }(window, document);
}else {
  modal({
    title: '提示',
    content: '如果想修改课程信息，请在列表页点击要修改的信息进入该页面；',
    width: '500px',
    height: 'auto',
    cancelBtn: false,
    confirmBtn: true,
    cancelText: '取消',
    confirmText: '确认',
    cancelCallback: function() {},
    confirmCallback: function() {
      window.location = 'courselist.html'
    }
  });
}
